package com.example.util;
//=====================AI生成=====================
public class UserIdGeneratorUtils {

    // 使用单例模式确保全局唯一性
    private static final Snowflake snowflake = new Snowflake(1); // workerId = 1

    /**
     * 静态方法返回一个 long 型 userId（雪花算法）
     */
    public static long SnowflakeIdGenerator() {
        return snowflake.nextId();
    }

    /**
     * 雪花算法内部类
     */
    private static class Snowflake {
        // 系统时间回拨容忍度（毫秒）
        private long nodeIdBits = 10L;
        private long sequenceBits = 12L;

        private long maxSequence = ~(-1L << sequenceBits);

        private long nodeIdShift = sequenceBits;
        private long timestampLeftShift = sequenceBits + nodeIdBits;

        private long lastTimestamp = -1L;
        private long sequence = 0L;
        private final long nodeId;

        public Snowflake(long nodeId) {
            if (nodeId > (~(-1L << nodeIdBits)) || nodeId < 0) {
                throw new IllegalArgumentException("节点ID超出范围");
            }
            this.nodeId = nodeId << sequenceBits;
        }

        public synchronized long nextId() {
            long timestamp = System.currentTimeMillis();

            if (timestamp < lastTimestamp) {
                throw new RuntimeException("时钟回拨");
            }

            if (timestamp == lastTimestamp) {
                sequence = (sequence + 1) & maxSequence;
                if (sequence == 0) {
                    timestamp = tilNextMillis(lastTimestamp);
                }
            } else {
                sequence = 0;
            }

            lastTimestamp = timestamp;

            return (timestamp << timestampLeftShift)
                    | nodeId
                    | sequence;
        }

        private long tilNextMillis(long lastTimestamp) {
            long timestamp = System.currentTimeMillis();
            while (timestamp <= lastTimestamp) {
                timestamp = System.currentTimeMillis();
            }
            return timestamp;
        }
    }
}
